import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:h_flutter_119/api/Api.dart';
import 'package:h_flutter_119/http/httpUtils.dart';
import 'package:h_flutter_119/page/find/model/ItemList.dart';
import 'package:h_flutter_119/route/route_utils.dart';

import '../model/Focus_Entity.dart';
import '../model/Focus_Item_Entity.dart';

class AttentionPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AttentionPageState();
}

class _AttentionPageState extends State<AttentionPage> {
  List<FocusItemEntity> dataList = [];
  late EasyRefreshController _easyRefreshController;
  final ScrollController _scrollController = ScrollController();
  int _page = 0;

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController(
        controlFinishRefresh: true, controlFinishLoad: true);

    _getFoucsData();
  }

  void _getFoucsData() async {
    if (_page == 0) {
      dataList.clear();
    }
    var response = await HttpUtils.getInstance()
        .get(Api.FOUCS_DATA, data: {"start": _page});
    var entity = FocusEntity.fromJson(json.decode(response.toString()));
    setState(() {
      dataList.addAll(entity.itemList ?? []);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _easyRefreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: Visibility(
          visible: dataList.length > 20,
          child: FloatingActionButton(
            onPressed: () {
              _scrollController.animateTo(0,
                  duration: const Duration(milliseconds: 200),
                  curve: Curves.ease);
            },
            child: const Icon(
              Icons.arrow_upward,
              color: Colors.white,
            ),
          )),
      body: EasyRefresh.builder(
          controller: _easyRefreshController,
          header: PhoenixHeader(),
          footer: PhoenixFooter(),
          onLoad: () {
            _page += 2;
            _getFoucsData();

            _easyRefreshController.finishLoad();
          },
          onRefresh: () async {
            _page = 0;
            _getFoucsData();
            _easyRefreshController.finishRefresh();
            _easyRefreshController.resetFooter();
          },
          childBuilder: (context, physics) {
            return ListView.builder(
              itemBuilder: (context, index) {
                return _FoucsItem(dataList[index]);
              },
              itemCount: dataList.length,
              physics: physics,
              controller: _scrollController,
            );
          }),
    );
  }

  Widget _FoucsItem(FocusItemEntity data) {
    return Column(
      children: [
        ListTile(
          leading: GestureDetector(
            child: ClipOval(
              child: Image.network(data.data?.header?.icon ?? "",
                  width: 80.w, height: 80.w),
            ),
            onTap: (){
              goPhotoPreview(context, data.data?.header?.icon??"");
            },
          ),
          title: Text(
            data.data?.header?.title ?? "",
            style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontSize: 30.sp,
                overflow: TextOverflow.ellipsis),
            maxLines: 1,
          ),
          subtitle: Text(
            data.data?.header?.description ?? "",
            style: TextStyle(
                color: Colors.black,
                fontSize: 27.sp,
                overflow: TextOverflow.ellipsis),
            maxLines: 1,
          ),
        ),
        SizedBox(
          height: 400.w,
          child: ListView.builder(
              itemBuilder: (context, index) {
                return _InnerItem(data.data?.itemList?[index]);
              },
              itemCount: data.data?.itemList!.length,
              scrollDirection: Axis.horizontal),
        )
      ],
    );
  }

  Widget _InnerItem(ItemList? innerData) {
    return innerData == null
        ? SizedBox(width: 0, height: 0)
        : GestureDetector(
            onTap: () {
              Map<String, dynamic> map = Map();
              map["playUrl"] = innerData.data?.playUrl ?? "";
              map["coverUrl"] = innerData.data?.cover?.feed ?? "";
              map["videoId"] = innerData.data?.id ?? "";
              goVideoDetail(context, map);
            },
            child: Container(
              margin: EdgeInsets.only(left: 16.w),
              width: 500.w,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Stack(
                    children: [
                      Hero(
                          tag: innerData.data?.id ?? "",
                          child: Image.network(
                            innerData.data?.cover?.feed ?? "",
                            width: 500.w,
                          )),
                      Positioned(
                          left: 0,
                          top: 0,
                          child: Container(
                            height: 42.w,
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(left: 25.w, right: 33.w),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(5.w),
                                  bottomRight: Radius.circular(42.w)),
                              color: Colors.red,
                            ),
                            child: Text(
                              innerData.data?.category ?? "",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 24.sp),
                            ),
                          )),
                    ],
                  ),
                  Text(
                    innerData.data?.title ?? "",
                    style: TextStyle(
                        fontSize: 32.w,
                        fontWeight: FontWeight.bold,
                        overflow: TextOverflow.ellipsis),
                    maxLines: 1,
                  ),
                  Text(
                    innerData.data?.description ?? "",
                    style: TextStyle(overflow: TextOverflow.ellipsis),
                    maxLines: 1,
                  ),
                ],
              ),
            ),
          );
  }
}
